//
//  HNSH_FeedbackViewController.m
//  HNSH_SingleProject
//
//  Created by 李宇廷 on 2023/3/7.
//

#import "HNSH_FeedbackViewController.h"

//view
#import "CGXStringPickerView.h"
#import "HNSH_FeedbackCell.h"
#import "HNSH_FeedbackHeaderView.h"
#import "HNSH_FeedbackFooterView.h"

@interface HNSH_FeedbackViewController ()<UIImagePickerControllerDelegate, UINavigationControllerDelegate>
{
    HNSH_FeedbackHeaderView * headerView;
}
@property (nonatomic, strong)UIImagePickerController * imagePicker;
@property (nonatomic, strong)NSMutableArray * imagesArray;
/** */
@property (nonatomic, copy)NSArray * typesArray;
/** */
@property (nonatomic, copy)NSString * type;

@end

static NSString * HNSH_FeedbackCellID = @"HNSH_FeedbackCellID";
static NSString * HNSH_FeedbackHeaderViewID = @"HNSH_FeedbackHeaderViewID";
static NSString * HNSH_FeedbackFooterViewID = @"HNSH_FeedbackFooterViewID";

@implementation HNSH_FeedbackViewController


- (void)viewDidLoad{
    [super viewDidLoad];
    
    [self showNavTitle:@"意见反馈" showLeftItem:YES];
    
    [self loadConfigData];
    
    [self addAllViews];
    
    [self configCollectionCell];
}

#pragma mark - Myself Methods
- (void)addAllViews{
    [self.view addSubview:self.collectionView];
}

- (void)showImageSheet{
    [self.view endEditing:YES];
    UIAlertController * cameraAlert = [UIAlertController alertControllerWithTitle:@"请选择" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction * camera = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self showCamera];
    }];
    UIAlertAction * photo = [UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self showPhotosAlbum];
    }];
    UIAlertAction * cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    [cameraAlert addAction:camera];
    [cameraAlert addAction:photo];
    [cameraAlert addAction:cancel];
    [self presentViewController:cameraAlert animated:YES completion:nil];
}

/** 拍照 */
- (void)showCamera{
    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
        UIAlertController * a = [UIAlertController alertControllerWithTitle:@"提示" message:@"无相机设备" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction * cancel = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        }];
        [a addAction:cancel];
        [self presentViewController:a animated:YES completion:nil];
        return;
    }
    self.imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
    self.imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    [self presentViewController:self.imagePicker animated:YES completion:nil];
}

/** 相册选择 */
- (void)showPhotosAlbum{
    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]){
        UIAlertController * a = [UIAlertController alertControllerWithTitle:@"提示" message:@"设备无相册" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction * cancel = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        }];
        [a addAction:cancel];
        [self presentViewController:a animated:YES completion:nil];
        return;
    }
    self.imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    self.imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    [self presentViewController:self.imagePicker animated:YES completion:nil];
}

//MARK: 获取退款类型和原因
- (void)loadConfigData{
    [HNSH_UserNetServer requestUserAdviseConfigSuccess:^(ST_BaseNetModel * _Nullable responseObject) {
        if (responseObject.code == 0) {
            NSArray * list = responseObject.resultset;
            self.typesArray = list;
        }
    } Failure:^(NSError * _Nullable error) {
        
    }];
}

- (void)chooseType{
    [self.view endEditing:YES];
    NSArray * array = [self getTypesArray];
    if (!array || !array.count) {
        [self loadConfigData];
        [self.view makeToast:@"请选择反馈类型"];
        return;
    }
    [CGXStringPickerView showStringPickerWithTitle:@"反馈类型" DataSource:array DefaultSelValue:nil IsAutoSelect:NO Manager:nil ResultBlock:^(id selectValue, id selectRow) {
        self.type = selectValue;
        [self.collectionView reloadData];
    }];
}

- (NSArray *)getTypesArray{
    NSMutableArray * arr = [NSMutableArray new];
    for (NSDictionary * dic in self.typesArray) {
        NSString * refundName = dic[@"name"];
        [arr addObject:refundName];
    }
    return arr.copy;
}

- (NSString *)getConfigId{
    for (NSDictionary * dic in self.typesArray) {
        NSString * refundName = dic[@"name"];
        if ([refundName isEqualToString:self.type]) {
            return [NSString stringWithFormat:@"%@", dic[@"id"]];
        }
    }
    return nil;
}

#pragma mark - Getter Methods
- (UIImagePickerController *)imagePicker{
    if (!_imagePicker) {
        _imagePicker = [[UIImagePickerController alloc] init];
        _imagePicker.delegate = self;
        _imagePicker.allowsEditing = YES;
    }
    return _imagePicker;
}

- (NSMutableArray *)imagesArray{
    if (!_imagesArray) {
        _imagesArray = [@[] mutableCopy];
    }
    return _imagesArray;
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    [picker dismissViewControllerAnimated:YES completion:^{
        NSData * data = UIImageJPEGRepresentation([info objectForKey:UIImagePickerControllerOriginalImage], 0.5);
        [self commitImgToAliyunOSS:data];
    }];
}

/** 上传图片到七牛 */
- (void)commitImgToAliyunOSS:(NSData *)imgData{
    UIImage * image = [UIImage imageWithData:imgData];
    [DLUploadImageTool uploadImage:image progress:nil success:^(NSString *url) {
        if (url && url.length) {
            [self.imagesArray addObject:url];
        }
        [self.collectionView reloadData];
    } failure:^(NSError *error) {
        [self.view makeToast:@"图片上传失败"];
    }];
}

- (void)commit{
    NSString * phone = headerView.phone;
    NSString * detail = headerView.detail;
    NSArray * imgsArr = self.imagesArray.copy;
    if (![self.type isNotBlank]) {
        [self.view makeToast:@"请选择反馈类型"];
        return;
    }
    if (![phone isNotBlank]) {
        [self.view makeToast:@"请输入手机号"];
        return;
    }
    if (![NSString isValidateMobileWithPhone:phone]) {
        [self.view makeToast:@"手机号格式不正确"];
        return;
    }
    if (![detail isNotBlank]) {
        [self.view makeToast:@"请输入反馈内容"];
        return;
    }
    NSString * config_id = [self getConfigId];
    NSDictionary * params = @{@"config_id":config_id, @"phone":phone, @"content":detail, @"image_urls":imgsArr};
    [HNSH_UserNetServer requestUserAdviseAddWithParams:params success:^(ST_BaseNetModel * _Nullable responseObject) {
        if (responseObject.code == 0) {
            [self.view makeToast:@"反馈成功"];
            [self.navigationController popViewControllerAnimated:YES];
        }
    } Failure:^(NSError * _Nullable error) {
        
    }];
}

- (void)configCollectionCell {
    [self.collectionView registerClass:[HNSH_FeedbackHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:HNSH_FeedbackHeaderViewID];
    [self.collectionView registerClass:[HNSH_FeedbackFooterView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:HNSH_FeedbackFooterViewID];

    [self.collectionView registerClass:[HNSH_FeedbackCell class] forCellWithReuseIdentifier:HNSH_FeedbackCellID];
}

#pragma mark - UICollectionViewDelegate Methods
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (self.imagesArray.count >= 6) {
        return 6;
    } else {
        return self.imagesArray.count + 1;
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    HNSH_FeedbackCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:HNSH_FeedbackCellID forIndexPath:indexPath];
    if (self.imagesArray.count && (self.imagesArray.count > indexPath.row)) {
        cell.imageString = self.imagesArray[indexPath.row];
    }
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (self.imagesArray.count <= indexPath.row) {
        [self showImageSheet];
    }
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake(65, 65);
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(0, 15, 0, 15);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 0;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 15;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    if (kind == UICollectionElementKindSectionHeader) {
        HNSH_FeedbackHeaderView * view = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:HNSH_FeedbackHeaderViewID forIndexPath:indexPath];
        view.type = self.type;
        headerView = view;
        
        WeakSelf(weakSelf);
        view.chooseTypeBlock = ^{
            [weakSelf chooseType];
        };
        return view;
    } else {
        HNSH_FeedbackFooterView * view = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:HNSH_FeedbackFooterViewID forIndexPath:indexPath];
        WeakSelf(weakSelf);
        view.commitFeedbackBlock = ^{
            [weakSelf commit];
        };
        return view;
    }
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    return CGSizeMake(collectionView.frame.size.width, 290 + 51);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
    return CGSizeMake(collectionView.frame.size.width, 100);
}

@end
